
#! /usr/bin/python

import sys
import os
import time
import random
#sys.path.append('..'+os.sep+'trunk')
sys.path.append('../../../')
from spade import *
class Example(Agent.Agent):
    def _setup(self):
        entry = "Starting Organization Behaviour"
     #   self.info=[{"Recurso":"Restaurant","Nombre":"Restaurante1","type":"Italiano","Calle":"lacalle"}]


    def _process(self):
       pass
class MyCongregation(Organization.Congregation):
    pass

class MyTeam(Unit.Team):

    def _process(self):
        if self.state=="available":
            goal=eval(self.getGoal())
            precio=goal["CurrentPrice"]
            comprador=goal["Buyer"]
            min=self.getMinAgents()
            agents=self.getNumberOfAgents()
            #print precio,comprador,min,agents
            if self.myAgent.dinero>precio+self.myAgent.incremento and comprador!=self.myAgent.getAID().getName() and min<=agents:
                #enviamos un mensaje con la nueva oferta
                mess=ACLMessage.ACLMessage()
                mess.setPerformative("inform")
                mess.setContent(str(precio+self.myAgent.incremento))
                #print mess
                self.sendMessage(mess)


"""
    def entryUnitTest(self,sender,desc=None):
      type=""
      subtype=""
      for l in desc:
          if l["name"]=="units":
              u=str(l["value"])
              u=int(u)
              self.unidades=self.unidades+u
              return self.entrada
      return False
"""

if __name__ == "__main__":
    a="comprador"
    if len(sys.argv)>1:
        max=sys.argv[1]
    else: max=5
    max=int(max)+1
    for n in xrange(1,max):
        agent = a+str(n)+"@apolo.dsic.upv.es"
        #agent = "agent@thx1138.dsic.upv.es"
        #agent = "agent@tatooine.dsic.upv.es"
        b = Example(agent,"pasword")
        b.start()
        b.dinero=random.randint(100,500)
        b.incremento=random.randint(5,100)
        continua=True
        while continua:
            list=b.getOrganizationList()
            for i in list:
                #print i
                info=b.getOrganizationInfo(i)
                #print info
                goal=info["goal"]
                g=eval(goal)
                if g.has_key("goal") and g["goal"]=="auction":
                    o=MyCongregation(b,nick=a+str(n), name=i)
                    b.joinOrganization(o)
                    l=o.getUnitList()
                    if l!=[]:
                        i=random.randint(0,len(l)-1)
                        b.producto=l[i]
                        print agent,b.dinero,b.incremento,b.producto
                        entry=o.requestEntryUnit(l[i])
                        if entry:
                            u=MyTeam(b,nick=a+str(n), name=b.producto)
                            o.joinUnit(u)
                            continua=False







